import { Controller } from 'egg';
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const DEFAULTOVERTIME = 30;

export default class RoleController extends Controller {
  /**
   * @api {get} role/list 获取角色列表
   *  
   * @apiName list
   * @apiGroup Role
   * @apiParam {Number} [pageNo] 页码
   * @apiParam {Number} [pageSize] 页数
   * @apiHeaderExample {json} headers:
   *     {
   *       "token": "admin_token"
   *     }
   * @apiDescription 获取角色列表
   * 
   */
  public async list() {
    let { pageNo, pageSize } = this.ctx.request.query;
    let pageObject = this.ctx.helper.changePage(pageNo, pageSize);
    await this.ctx.model.Role.findAndCountAll({
      limit: pageObject.limit,
      offset: pageObject.offset
    })
      .then(data => {
        this.ctx.response.body = {
          code: 200,
          data: data.rows,
          total: data.count,
          status: '成功'
        };
      });
  }

  /**
   * @api {post} role/add 添加角色
   *  
   * @apiName add
   * @apiGroup Role
   * @apiDescription 添加角色
   * 
   * @apiParam {String} rolename 角色名
   * @apiParam {String} text 角色中文简称
   * @apiParam {String} limit 用户权限
   * @apiParam {Number} [overTime] 过期时间(天)
   * @apiParam {Number} visitMaxCount 用户最大可下载数(每天)
   */
  public async add(ctx) {
    let { rolename, text, limit, visitMaxCount, overTime } = ctx.request.body;
    try {
      let data = await ctx.model.Role.findAll();
      let mapArray = data.map(item => {
        return parseInt(item.roleId);
      });
      let maxValue = Math.max.apply(Math, mapArray.length === 0 ? [0] : mapArray);
      let new_role_id = (maxValue + 1);
      let role = await ctx.model.Role.create({
        name: rolename,
        text: text,
        limit: limit,
        roleId: new_role_id,
        overTime: overTime ? parseInt(overTime) : DEFAULTOVERTIME,
        visitMaxCount: parseInt(visitMaxCount)
      });
      await this.app.redis.hset('visitMax', `${new_role_id}`, parseInt(visitMaxCount));
      await this.app.redis.hset('overTime', `${new_role_id}`, parseInt(overTime) || DEFAULTOVERTIME);
      this.ctx.response.body = {
        code: 200,
        data: role,
        status: '成功'
      };
    } catch (msg) {
      this.ctx.response.body = msg;
    }

  }

  /**
   * @api {post} role/update 修改角色
   *  
   * @apiName update
   * @apiGroup Role
   * @apiDescription 修改角色
   * @apiHeaderExample {json} headers:
   *     {
   *       "token": "admin_token"
   *     }
   * 
   * @apiParam {String} roleId 角色id
   * @apiParam {String} rolename 角色名
   * @apiParam {String} text 角色中文简称
   * @apiParam {String} limit 用户权限
   * @apiParam {Number} [overTime] 过期时间(天)
   * @apiParam {Number} visitMaxCount 用户最大可下载数(每天)
   * 
   */
  public async update(ctx) {
    let { rolename, text, limit, roleId, visitMaxCount, overTime } = ctx.request.body;
    try {
      await ctx.model.Role.update({
        name: rolename,
        text: text,
        limit: limit,
        overTime: overTime ? parseInt(overTime) : DEFAULTOVERTIME,
        visitMaxCount: parseInt(visitMaxCount)
      },
        {
          where: {
            roleId: parseInt(roleId)
          }
        });
      await this.app.redis.hset('visitMax', roleId, parseInt(visitMaxCount));
      await this.app.redis.hset('overTime', roleId, parseInt(overTime) || DEFAULTOVERTIME);
      this.ctx.response.body = {
        code: 200,
        status: '修改成功'
      };
    } catch (error) {
      this.ctx.response.body = error;
    }
  }

  /**
   * @api {get} role/delete 删除角色
   *  
   * @apiName delete
   * @apiGroup Role
   * @apiDescription 删除角色
   * @apiHeaderExample {json} headers:
   *     {
   *       "token": "admin_token"
   *     }
   *
   * 
   * @apiParam {String} roleId 角色ID
   * 
   */
  public async delete(ctx) {
    let { roleId } = ctx.query;
    try {
      if (roleId === undefined || roleId === '' || roleId === []) {
        throw ctx.helper.getErrorMsg(207);
      }
      let queryArray: number[] = [];
      let postType = await ctx.helper.whatType(roleId);
      if (postType === 'String' || postType === 'Number') {
        queryArray.push(parseInt(roleId));
      } else if (postType === 'Array') {
        roleId.forEach(id => {
          queryArray.push(parseInt(id));
        });
      }
      // 判断是否可以删除角色
      let count = await ctx.model.User.count({
        where: {
          roleId: {
            [Op.or]: queryArray
          }
        }
      });
      if (count === 0) {
        await this.app.redis.hdel('visitMax', `${roleId}`);
        await this.app.redis.hdel('overTime', `${roleId}`);
        await ctx.model.Role.destroy({
          where: {
            roleId: {
              [Op.or]: queryArray
            }
          }
        })
          .then(() => {
            ctx.response.body = {
              code: 200,
              status: '成功'
            };
          });
      } else {
        throw ctx.helper.getErrorMsg(212);
      }

    } catch (info) {
      ctx.response.body = info;
    }
  }
}
